using System;
using System.Reflection;

using TrueCode.DependencyManager.BuildActions.Instantiating;


namespace TrueCode.DependencyManager.Services.Instantiating
{
  public class ByParameterTypesCtorProvider : IConstructorProvider
  {
    private readonly Type[] _types;

    public ByParameterTypesCtorProvider( params Type[] types )
    {
      _types = types;
    }

    public ConstructorInfo GetConstructor( Type type )
    {
      var constructors = type.GetConstructors();

      ConstructorInfo chosenConstructor = null;
      foreach( var constructor in constructors )
      {
        if( Match( constructor.GetParameters() ) )
        {
          chosenConstructor = constructor;
          break;
        }
      }
      return chosenConstructor;
    }

    private bool Match( ParameterInfo[] parameters )
    {
      var match = false;
      if( _types.Length == parameters.Length )
      {
        match = true;
        for( int i = 0; i < _types.Length; i++ )
        {
          if( _types[ i ] != parameters[ i ].ParameterType )
          {
            match = false;
            break;
          }
        }
      }
      return match;
    }
  }
}